<template>
  <div class="worflowTable" id="worflowTableContent">
    <!-- 功能按钮 -->
    <div class="sensitiveWord_button">
      <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('creatAble')" @click="addOREidtRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>
      <div class="searchContent">
        <div>
          <span class="flowScene_label">应用场景：</span>
          <a-select v-model:value="flowScene" style="width: 120px" :options="flowSceneStatus" :style="{ width: '112px' }"
            @select="fetchWorkFlowList">
          </a-select>
        </div>
        <div class="searchName">
          <a-input v-model:value="searchworkFlowName" placeholder="请输入工作流名称" style="width: 192px">
            <template #suffix>
              <i class="iconfont icon-search" @click="fetchWorkFlowList()"></i>
            </template>
          </a-input>
        </div>
      </div>
    </div>
    <!-- 工作流的table表格 -->
    <baseTable :columns="columns.workFlowTableColumns" :dataSource="configData.records"
      :isShowPagination="isShowPagination" :total="configData.total" @changePage="changePage" :isSelect="true"
      :scroll="scroll" :rowSelection="1">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'flowScene'">
          <p v-if="record.flowScene == 1">内容发布</p>
          <p v-else-if="record.flowScene == 2">投票调查</p>
          <p v-else="record.flowScene == 3">领导信箱</p>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click="addOREidtRecord(record)">
            编辑
          </a>
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('setWorkflowAble') }"
            @click="setWorkFlow_G6(record)">
            流程设置
          </a>
          <a-popconfirm placement="topRight" ok-text="确定" cancel-text="取消" :disabled="!btnPerm.includes('deleteAble')"
            @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 356px">
                是否要删除此工作流，删除后，被该工作流绑定的审核案例将统一被驳回到初稿状态。请绑定新的工作流，否则被驳回的审核案例提交将不执行工作流审核。
              </p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
          </a-popconfirm>
        </template>
      </template>
    </baseTable>
  </div>
  <!-- 新建或编辑工作流模态框 -->
  <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
    @handleOk="buttonMessage" @handleCancle="isVisible = false" class="sensitive_modal">
    <template v-slot:body>
      <div>
        <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
          ref="workflowFrom" v-if="isVisible">
          <a-form-item :name="['flowName', 'value']" :label="formState.flowName.label" :rules="[formState.flowName.rule]">
            <a-input v-model:value="formState.flowName.value" :placeholder="formState.flowName.placeholder" show-count
              :maxlength="25" allow-clear ref="flowName_ref" />
          </a-form-item>
          <a-form-item :name="['flowScene', 'value']" :label="formState.flowScene.label"
            :rules="[formState.flowScene.rule]">
            <a-select v-model:value="formState.flowScene.value" style="width: 256px"
              :placeholder="formState.flowScene.placeholder"
              :options="formState.flowScene.options.map((item: any, index: number) => ({ value: item.value, label: item.label }))"
              @change="flowSceneChange"></a-select>
          </a-form-item>
          <a-form-item :label="formState.remark.label" class="remark">
            <a-textarea v-model:value="formState.remark.value" :placeholder="formState.remark.placeholder"
              :auto-size="{ minRows: 2, maxRows: 50 }" allow-clear maxlength="200" show-count />
          </a-form-item>
        </a-form>
      </div>
    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import { useRouter } from "vue-router";
import request from "@/api/index";
import { scrollType, configDataType, modeProp } from "@/type.d";
import { message } from "ant-design-vue";
import { checkrule } from "./formRuler";
import { routerPerm } from "@/utils/common";
// TS
interface dataSourceType {
  [propName: string]: any;
}
// form 验证
const checkrule_workFlowName = async (_rule: dataSourceType = {}, value: any) => {
  if (!value) {
    return Promise.reject(`${_rule.msg1}`);
  } else {
    var params = Object.assign(_rule.params, {
      flowName: formState.flowName.value,
      id: formState.id,
      flowScene: formState.flowScene.value,
    });
    if (_rule.api) {
      let res = await request[`${_rule.api}`](params);
      if (!res) {
        return Promise.reject(`${_rule.msg2}`);
      } else {
        return Promise.resolve();
      }
    }
  }
};
//data
const btnPerm = ref<any[]>([]);
//路由
const router = useRouter();
//页面头部
const searchworkFlowName = ref<string>("");
const flowSceneStatus = ref<dataSourceType["options"]>([
  // 应用场景
  {
    value: "",
    label: "全部",
  },
  {
    value: "1",
    label: "内容发布",
  },
  {
    value: "2",
    label: "投票调查",
  },

  {
    value: "3",
    label: "领导信箱",
  },
]);
const flowScene = ref<String>(""); // 筛选过滤表格数据
const flowName_ref = ref();
//表格相关数据
const isShowPagination = true; // 是否需要配分页器

const reqTelListOption = ref({
  //控制分页数据请求的变量集合
  pageNumber: 0,
  pageSize: 10,
  tplType: 1,
});
//编辑项

let scroll: scrollType = reactive({ y: "", isFixed: false });
//工作流表格数据
let configData = ref<configDataType>({ total: 0, size: 10, records: [] });

// const dataList = ref(dataSource.value.slice(0, 10))
// 模态框数据
const workflowFrom = ref<any>();
const isVisible = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "编辑工作流",
});

const formState = reactive<dataSourceType>({
  flowName: {
    value: "",
    rule: {
      required: true,
      validator: checkrule_workFlowName,
      trigger: ["blur"],
      msg1: "工作流名称不可为空！",
      msg2: "工作流名称已存在！",
      api: "uniqueWorkFlowName",
      id: "",
      params: {},
    },
    label: "工作流名称",
    placeholder: "请输入",
  },
  flowScene: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      validator: checkrule,
      msg1: "请选择应用场景！",
      api: "uniqueWorkFlowName",
      id: "",
      params: {},
    },
    options: [
      {
        value: 1,
        label: "内容发布",
      },
      {
        value: 2,
        label: "投票调查",
      },
      /* interact-mailbox start */
      {
        value: 3,
        label: "领导信箱",
      },
      /* interact-mailbox end */
    ],
    label: "应用场景",
    placeholder: "请选择",
  },
  remark: {
    value: "",
    label: "工作流描述",
    placeholder: "不超过200个字",
  },
  id: "",
});

const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
// flowSceneChange
const flowSceneChange = () => {
  flowName_ref.value.focus();
  flowName_ref.value.blur();
};
//onmounted
onMounted(() => {
  btnPerm.value = routerPerm();
  fetchWorkFlowList();
});

//methods
//获取工作流的分页列表数据展示
const fetchWorkFlowList = async (data = "") => {
  const postData: dataSourceType = {
    pageNumber: reqTelListOption.value.pageNumber || 0,
    pageSize: reqTelListOption.value.pageSize || 10,
  };
  searchworkFlowName.value ? (postData.flowName = searchworkFlowName.value) : "";
  flowScene.value ? (postData.flowScene = flowScene.value) : "";
  const telData = await request.fetchWorkFlowTable(postData);
  let reqData = telData;
  configData.value.total = reqData.total;
  configData.value.size = reqData.size;
  configData.value.records = reqData.records || [];
  nextTick(() => {
    scroll.y = getTableScroll(130, "worflowTableContent").y;
    scroll.isFixed = getTableScroll(130, "worflowTableContent").isFixed;
  });
};
// 添加或编辑工作流
const addOREidtRecord = (record: dataSourceType) => {
  if (record.id) {
    if (!btnPerm.value.includes("editAble")) return;
  }
  isVisible.value = true;
  modAlProps.title = record.id ? "编辑工作流" : "新建工作流";
  formState.flowName.value = record ? record.flowName : "";
  formState.flowScene.value = record ? record.flowScene : "";
  formState.remark.value = record ? record.remark : "";
  formState.id = record ? record.id : "";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};
// 设置工作流流程图

const setWorkFlow_G6 = (record: dataSourceType) => {
  if (!btnPerm.value.includes("setWorkflowAble")) return;
  router.push({
    path: "/config/workFlow/detail",
    query: {
      id: record.id,
      flowName: record.flowName,
    },
  });
};
//删除工作流
const confirmDelete = (record: dataSourceType) => {
  const params = {
    id: record.id,
  };
  request
    .deleteWorkFlowRable(params)
    .then((res: dataSourceType) => {
      if (res.code == "00000 00000") {
        fetchWorkFlowList();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const buttonMessage = () => {
  const params = {
    flowName: formState.flowName.value,
    flowScene: formState.flowScene.value,
    id: formState.id,
    remark: formState.remark.value,
  };
  workflowFrom.value.validate().then((res: any) => {
    request[!formState.id ? "addWorkFlowRecord" : "editWorkFlowTable"](params)
      .then((res: dataSourceType) => {
        if (res.code == "00000 00000") {
          fetchWorkFlowList();
          message.success(res.message);
        } else {
          message.error(res.message);
        }
        isVisible.value = false;
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  });
};
// 获取分页的改变
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let { pageCurrent, pageSize } = data;
  reqTelListOption.value.pageNumber = pageCurrent;
  reqTelListOption.value.pageSize = pageSize;
  fetchWorkFlowList();
};

//computed
</script>

<style lang="less" scoped>
.worflowTable {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;
  overflow: hidden;

  .sensitiveWord_button {
    padding-bottom: 16px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;
      display: flex;

      .flowScene_label {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
      }

      .searchName {
        font-size: 14px;
        color: #333;
        margin-left: 16px;
      }

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  .eidtRecords {
    margin-right: 16px;
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }
}

:deep(.ant-form-item) {
  width: 596px;
  display: flex;

  // margin-left: 28px;
  .ant-form-item-control {
    width: 494px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 94px;
    text-align: right;
  }
}

:deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
  margin-bottom: 0px;
}
</style>
<style>
.ant-tooltip {
  max-width: 700px;
}

.worflowTable .ant-table-wrapper table>thead>tr>th:nth-child(1) {
  padding-left: 16px;
}

.worflowTable .ant-table-wrapper table>tbody>tr>td:nth-child(1) {
  padding-left: 16px;
  padding-right: 16px;
}
</style>
